//
//  HomeSeeFileWebViewViewController.m
//  ZJControlsClass
//
//  Created by wandoufo on 2024/12/23.
//

#import "HomeSeeFileWebViewViewController.h"
#import <WebKit/WebKit.h>

@interface HomeSeeFileWebViewViewController () <WKNavigationDelegate, WKUIDelegate>

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) UIBarButtonItem *downloadButton;
@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask;

@end

@implementation HomeSeeFileWebViewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self setupNavigationItems];
    [self loadWebContent];
}

- (void)setupUI {
    // 配置 WKWebView
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.allowsInlineMediaPlayback = YES;
    
    // 初始化 WKWebView
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    self.webView.allowsBackForwardNavigationGestures = YES;
    [self.view addSubview:self.webView];
    
    // 添加进度条
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 2)];
    self.progressView.progressTintColor = [UIColor blueColor];
    self.progressView.trackTintColor = [UIColor clearColor];
    [self.view addSubview:self.progressView];
    
    // 监听进度
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)setupNavigationItems {
    // 创建下载按钮
    self.downloadButton = [[UIBarButtonItem alloc] initWithImage:[UIImage systemImageNamed:@"arrow.down.circle"]
                                                          style:UIBarButtonItemStylePlain
                                                         target:self
                                                         action:@selector(downloadButtonTapped)];
    self.navigationItem.rightBarButtonItem = self.downloadButton;
}

- (void)loadWebContent {
    if (self.fileUrl.length > 0) {
        NSURL *url = [NSURL URLWithString:self.fileUrl];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [self.webView loadRequest:request];
    }
}

- (void)downloadButtonTapped {
    if (!self.fileUrl.length) {
        [self showToast:@"下载地址无效"];
        return;
    }
    
    // 显示确认对话框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"下载文件"
                                                                  message:@"确定要下载此文件吗？"
                                                           preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self startDownload];
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)startDownload {
    // 创建下载进度指示器
    UIProgressView *downloadProgress = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, 150, 2)];
    UIBarButtonItem *progressItem = [[UIBarButtonItem alloc] initWithCustomView:downloadProgress];
    self.navigationItem.rightBarButtonItem = progressItem;
    
    // 创建下载任务
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
                                                       delegate:self
                                                  delegateQueue:[NSOperationQueue mainQueue]];
    
    self.downloadTask = [session downloadTaskWithURL:[NSURL URLWithString:self.fileUrl]];
    [self.downloadTask resume];
    
    // 监听下载进度
    [NSTimer scheduledTimerWithTimeInterval:0.1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        if (self.downloadTask.countOfBytesExpectedToReceive > 0) {
            float progress = (float)self.downloadTask.countOfBytesReceived / (float)self.downloadTask.countOfBytesExpectedToReceive;
            downloadProgress.progress = progress;
        }
    }];
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.webView.estimatedProgress;
        if (self.progressView.progress == 1.0) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.hidden = YES;
            });
        } else {
            self.progressView.hidden = NO;
        }
    }
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    self.progressView.hidden = NO;
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    self.title = webView.title;
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    [self showErrorAlert:error];
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    [self showErrorAlert:error];
}

#pragma mark - NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    // 获取文件名
    NSString *fileName = [self.fileUrl lastPathComponent];
    if (!fileName.length) {
        fileName = @"downloaded_file";
    }
    
    // 创建目标路径
    NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *destinationPath = [documentsPath stringByAppendingPathComponent:fileName];
    
    NSError *error;
    // 移动文件到目标路径
    [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:destinationPath] error:&error];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.navigationItem.rightBarButtonItem = self.downloadButton;
        
        if (error) {
            [self showToast:@"下载失败"];
        } else {
            [self showToast:@"下载成功"];
        }
    });
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    if (error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.navigationItem.rightBarButtonItem = self.downloadButton;
            [self showToast:@"下载失败"];
        });
    }
}

#pragma mark - Helper Methods
- (void)showErrorAlert:(NSError *)error {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"加载失败"
                                                                  message:error.localizedDescription
                                                           preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *retryAction = [UIAlertAction actionWithTitle:@"重试"
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * _Nonnull action) {
        [self loadWebContent];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"
                                                          style:UIAlertActionStyleCancel
                                                        handler:nil];
    
    [alert addAction:retryAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)showToast:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil
                                                                  message:message
                                                           preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [alert dismissViewControllerAnimated:YES completion:nil];
        });
    }];
}

#pragma mark - Memory Management
- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

@end
